package org.saratogaschools.edd.firefighter.client.activity;

import org.saratogaschools.edd.firefighter.client.ClientFactory;
import org.saratogaschools.edd.firefighter.client.place.AddDepartmentPlace;
import org.saratogaschools.edd.firefighter.client.place.SelectDepartmentPlace;
import org.saratogaschools.edd.firefighter.client.place.SelectRolePlace;
import org.saratogaschools.edd.firefighter.client.util.AsyncPlaceChange;
import org.saratogaschools.edd.firefighter.client.util.DepartmentDataProvider;
import org.saratogaschools.edd.firefighter.client.view.SelectDepartmentView;
import org.saratogaschools.edd.firefighter.shared.model.Department;
import org.saratogaschools.edd.firefighter.shared.model.FireFighter;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

public class SelectDepartmentActivity extends AbstractActivity implements SelectDepartmentView.Presenter {
	
	private FireFighter registrationCandidate;
	private ClientFactory clientFactory;
	private DepartmentDataProvider dataProvider;
	private SelectDepartmentView view;

	public SelectDepartmentActivity(SelectDepartmentPlace place,
			ClientFactory clientFactory) {
		this.registrationCandidate = place.getRegistrationCandidate();
		this.clientFactory = clientFactory;
		this.dataProvider = new DepartmentDataProvider(clientFactory.getService());
		this.view = new SelectDepartmentView();
		this.view.setNewDepartmentButtonEnabled(clientFactory.areAdvancedFeaturesActive());
		view.setPresenter(this);
	}

	@Override
	public void start(AcceptsOneWidget panel, EventBus eventBus) {
		view.setName(registrationCandidate.getName());
		panel.setWidget(view);
		dataProvider.addDataDisplay(view.getDepartmentDisplay());
	}

	@Override
	public void addDepartment() {
		GWT.runAsync(new AsyncPlaceChange(clientFactory, new AddDepartmentPlace(registrationCandidate)));
	}

	@Override
	public void selectDepartment(Department dpt) {
		String departmentKey = dpt.getEncodedKey();
		registrationCandidate.setDepartmentKey(departmentKey);
		GWT.runAsync(new AsyncPlaceChange(clientFactory, new SelectRolePlace(registrationCandidate)));
	}

}
